package edu.hrbu.kwaidu.aspect;

import edu.hrbu.kwaidu.annotation.HasPerms;
import edu.hrbu.kwaidu.constant.SystemConstant;
import edu.hrbu.kwaidu.exception.CustomException;
import edu.hrbu.kwaidu.util.CustomUtil;
import edu.hrbu.kwaidu.util.RedisUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;

import static edu.hrbu.kwaidu.constant.SystemConstant.EXCEPTION_NO_AUTH;

/**
 * @author xudengyu
 */
@Component
@Aspect
public class PermsAspect {

    @Resource
    private RedisUtil redisUtil;

    @Before("@annotation(hasPerms)")
    public void roleBefore(JoinPoint joinPoint, HasPerms hasPerms) {
        String[] needPerms = hasPerms.value();
        HttpServletRequest request = CustomUtil.getRequest();
        String token = request.getHeader(SystemConstant.REQ_HEADER_TOKEN);
        List<String> hasPermList = redisUtil.getPermsCache(token);
        boolean f = false;
        for (String needPermission : needPerms) {
            if (hasPermList.contains(needPermission)) {
                f = true;
                break;
            }
        }
        if (!f) throw new CustomException(EXCEPTION_NO_AUTH);
    }
}
